package cn.jhz.learn.blog.util;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.util.List;
import java.util.stream.Collectors;

public class TextUtil {

    private  TextUtil(){

    }
    private static final class TextUtilHolder {
        private static final TextUtil instance = new TextUtil();
    }

    public static TextUtil getInstance(){
        return TextUtilHolder.instance;
    }

    /**
     * 若输出结果需要保持原有顺序, 需要确保数据源是有序的结构
     * @param htmlList
     * @param length
     * @return
     */
    public List<String> getTextOverview(List<String> htmlList, Integer length){
       return htmlList.stream().map(html ->getTextOverview(html, length)).collect(Collectors.toList());
    }

    public String getTextOverview(String html, Integer length){
        if(StringUtils.isNotBlank(html)) {
            Document document = Jsoup.parse(html);
            String overview = document.text();

            if (overview.length() > length) {
                overview = overview.replace("  ", "");
                if (overview.length() > length)
                    overview = overview.substring(0, length);
            }

            return overview;
        }
        return html;
    }
}
